package com.yeook.ymax.ui.fragments;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.yeook.ymax.R;
import com.yeook.ymax.app.ApplicationYMAX;
import com.yeook.ymax.db.Database;
import com.yeook.ymax.db.SimpleCursorLoader;
import com.yeook.ymax.ui.activitys.ResponsiveUIActivity;
import com.yeook.ymax.ui.entity.WallaperView;

public class ImageGridFragment extends Fragment  implements LoaderCallbacks<Cursor> {
	//private int mImgRes;
	
	ResponsiveUIActivity activity = null;
	
	DisplayImageOptions options;
	
	int cateCode = -1;
	
	String title;
	
	private Database db = Database.getInstance();
	
	public ImageGridFragment() { }
	public ImageGridFragment(int _cateCode, String _title) {
		cateCode = _cateCode;
		title = _title;
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		activity = (ResponsiveUIActivity) getActivity();
		if (cateCode == -1 && savedInstanceState != null)
			cateCode = savedInstanceState.getInt("cateCode");
		
		activity.cateCode = cateCode;
		
		activity.setTitle(title);
		
		activity.wallaperViews.clear();
		
		View gv = inflater.inflate(R.layout.ac_image_grid, null);
		//XmlLoader xmlLoader = new XmlLoader();
		//activity.imageUrls = xmlLoader.getImageUrls(xmlLoader.praseXml());
		options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.ic_empty_small)
			.showImageForEmptyUri(R.drawable.ic_empty_small)
			.showImageOnFail(R.drawable.ic_error_small)
			.cacheInMemory().imageScaleType(ImageScaleType.EXACTLY)
			.cacheOnDisc()
			.bitmapConfig(Bitmap.Config.RGB_565)
			.build();

		activity.listView = (GridView) gv.findViewById(R.id.gridview);
		//((GridView) activity.listView).setAdapter(new ImageAdapter());
		activity.wallpaperLoader = activity.getSupportLoaderManager().initLoader(0, null, this);
		activity.wallpaperLoader.forceLoad();
		AdView adView = (AdView)gv.findViewById(R.id.adView);
        adView.loadAd(new AdRequest());
		return gv;
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("cateCode", activity.cateCode);
	}
	
	public class ImageAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			return activity.wallaperViews.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView imageView;
			if (convertView == null) {
				imageView = (ImageView) activity.getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
			} else {
				imageView = (ImageView) convertView;
			}
			
			imageView.setOnClickListener(new ImageViewClickListener(position));
			
			WallaperView wallaperView = activity.wallaperViews.get(position);
			
			SimpleDateFormat formatYear = new SimpleDateFormat("yyyy");
			String year = formatYear.format(wallaperView.getDate());
			
			SimpleDateFormat formatMonth = new SimpleDateFormat("MMdd");
			String month = formatMonth.format(wallaperView.getDate());
			
			String imageUrl = ApplicationYMAX.DEFAULTWEBSERVIC + "thumnail/" + year +"/" + month + "/" + wallaperView.getAttachmentId() + "_210x120";

			activity.imageLoader.displayImage(imageUrl, imageView, options);

			return imageView;
		}
	}
	
	class ImageViewClickListener implements OnClickListener
	{
		private int imagePosition;
		public ImageViewClickListener(int _imagePosition)
		{
			imagePosition = _imagePosition;
		}
		@Override
		public void onClick(View v) {
			activity.startImagePagerActivity(imagePosition);
		}
		
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {
		SimpleCursorLoader a = new SimpleCursorLoader(activity) {

			@Override
			public Cursor loadInBackground() {
				// TODO Auto-generated method stub
				return db.getWallpaperViews(activity.cateCode);
			}
			
		};
		return a;
	}
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		activity.wallaperViews.clear();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			WallaperView wallaperView = new WallaperView();
			wallaperView.setCateCode(cursor.getInt(6));
			wallaperView.setDescription(cursor.getString(2));
			wallaperView.setFileName(cursor.getString(5));
			wallaperView.setLable(cursor.getString(4));
			wallaperView.setUniqueId(cursor.getLong(3));
			wallaperView.setDate(new Date(cursor.getLong(7)));
			wallaperView.setAttachmentId(cursor.getLong(8));
			activity.wallaperViews.add(wallaperView);
		}
		
		if(activity.wallaperViews.size() == 0)
		{
			Toast toast= Toast.makeText(activity, activity.getString(R.string.loading_face_detection), Toast.LENGTH_SHORT);
			toast.show();
		}
		
		((GridView) activity.listView).setAdapter(new ImageAdapter());
	}
	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		activity.wallaperViews.clear();
		((GridView) activity.listView).setAdapter(new ImageAdapter());
	}
}
